package com.newcoder.community.controller;

import com.google.code.kaptcha.Producer;
import com.newcoder.community.pojo.User;
import com.newcoder.community.serverce.LoginTicketService;
import com.newcoder.community.serverce.UserService;
import com.newcoder.community.utill.CommunityConstant;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

@Controller
public class LogRegisterPage implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(LogRegisterPage.class);
    @Autowired
    private UserService userService;
    @Autowired
    private Producer kaptchaProducer;
    @Autowired
    private LoginTicketService loginTicketService;

    @GetMapping("/register")
    public String toRegisterPage() {
        return "/site/register";
    }

    @PostMapping("/register")
    public String getRegisterPath(Model model, User user) {
        Map<String, Object> map = userService.register(user);
        if (map == null || map.isEmpty()) {
            model.addAttribute("msg", "注册成功，我们已经向您发送了一封注册邮件请注意查收");
            model.addAttribute("target", "/index");
            System.out.println("发送邮件");
            return "/site/operate-result";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
            return "/site/register";
        }

    }


    @GetMapping("/login")
    public String toLoginPage() {
        return "/site/login";
    }

    @PostMapping("/login")
    public String login(String username, String password, String code, boolean rememberme,
                        Model model, HttpSession session, HttpServletResponse resp) {
        String kaptcha = (String) session.getAttribute("kaptcha");
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) ||!kaptcha.equalsIgnoreCase(code)) {
            model.addAttribute("codeMsg", "验证码不正确");
            return "/site/login";
        }
        int expiredSeconds = rememberme ? CommunityConstant.REMEMBER_EXPIRED_SECONDS : CommunityConstant.DEFAULT_EXPIRED_SECONDS;
        Map<String, String> map = loginTicketService.login(username, password, expiredSeconds);
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket"));
            cookie.setPath("/");
            cookie.setMaxAge(expiredSeconds);
            resp.addCookie(cookie);
            return "redirect:/index";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/login";
        }

    }
    @GetMapping("/logout")
    public String logOut(@CookieValue("ticket") String ticket){
        loginTicketService.logOut(ticket);
        return "redirect:/login";
    }

    @GetMapping("/activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code) {
        int activation = userService.activation(userId, code);
        if (activation == ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "激活成功，您可以登录了");
            model.addAttribute("target", "/login");
        } else if (activation == ACTIVATION_REPEAT) {
            model.addAttribute("msg", "无效账户，该账号已经注册！");
            model.addAttribute("target", "/index");

        } else if (activation == ACTIVATION_FAILURE) {
            model.addAttribute("msg", "注册失败，您输入的验证码输入错误");
            model.addAttribute("target", "/index");
        }
        return "/site/operate-result";

    }

    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse resp, HttpSession session) {
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);
        session.setAttribute("kaptcha",text);
        resp.setContentType("image/png");
        try {
            ServletOutputStream outputStream = resp.getOutputStream();
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            logger.error("获取验证码失败" + e.getMessage());
        }


    }


}
